import constant from "./constant.js";
import ToolApis from "@/tool/http/ToolApis.js";
import toolVuex from "@/tool/vuex/ToolVuex.js";

async function init(code, metadata, dsId = toolVuex.state._dsId) {
	let config = {};
	try {
		let res = await import(`./rules/${code}/${dsId || ""}rule.js`);
		config = await res.default(metadata);
	} catch (e) {
		console.error(e);
	}

	config.extendField = config.extendField || "extend_json";
	config.baseField = config.baseField || [];
	config.extendFields = config.extendFields || [];
	config.formOnChange = config.formOnChange || (() => {});
	config.listFieldExtend = config.listFieldExtend || (async () => {});

	metaMerge(metadata, config.metaConfig);
	await metaBuild(metadata, dsId);
	return config;
}

export default {
	init
}

async function metaBuild(metadata, dsId) {
	for (let i = 0; i < metadata.length; i++) {
		let meta = metadata[i];
		if (!meta.dictList && constant[meta.type]) {
			meta.dictList = constant[meta.type];
		}
		if (!dsId) {
			if (meta.name === "tenant_id") {
				meta.dictList = await ToolApis.dictTenant();
			}
		}
	}
}

function metaMerge(metadata, config) {
	if (!config) return;
	metadata.forEach(meta => {
		let metaConfig = config[meta.name];
		if (!metaConfig) {
			return;
		}
		if (metaConfig.dictList === null) {
			delete meta.dictList;
		}
		Object.assign(meta, metaConfig);
	})
}
